import { toSuccess, useEntityManager, useRedis } from "@sker/core";
import { KsAccount, KsDevice, KsLiveRoom, KsRedPacket } from "@sker/entities";
import { useData } from "@sker/runtime";
import axios from "axios";
import dayjs from "dayjs";
import { DependencyContainer } from "tsyringe";
import { Between } from "typeorm";
import { z } from "zod";
import { Core } from "./core/core";
import { addRoomInfo2 } from "./kwai/kwaiHelper";
// 目前在用
async function getRealLink(link: string) {
    try {
        const response = await axios.get(link)
        const [path, query] = response.request.path.split(`?`)
        const res = path.match(/fw\/live\/(.*)/)
        if (res && res.length > 0) {
            const [, ksid] = res;
            const params: any = {}
            query.split('&').map(key => {
                const [name, value] = key.split('=');
                params[name] = value;
            });
            return { ...params, ksid };
        }
    } catch (e) {
        return {}
    }
}
export default async (injector: DependencyContainer) => {
    const input = z.object({
        name: z.optional(z.string()),
        link: z.optional(z.string()),
        online: z.optional(z.number()),
        openTime: z.string(),
        readPacketCount: z.optional(z.number()),
        rank: z.optional(z.string()),
        redPackets: z.array(z.any()),
        ksid: z.optional(z.string()),
        userId: z.optional(z.string()),
        shareObjectId: z.optional(z.string()),
        category: z.optional(z.string()),
        uuid: z.optional(z.string())
    });
    const body = input.parse(useData())
    if (!body.link) {
        return toSuccess({})
    }
    let data = body;
    // room
    let { ksid, userId, name, redPackets, shareObjectId, online, openTime, link, rank, category } = data;
    if (!userId) {
        return toSuccess(`失败`)
    }

    /**
     * 出入数据库
     */
    const room_id = await useEntityManager(async m => {
        const device = await m.findOne(KsDevice, { where: { uuid: body.uuid } })
        if (!device) return;
        const owner = device.owner
        // 账户
        let room = await m.findOne(KsLiveRoom, { where: { link: link } })
        if (userId) {
            const ksAccount = await m.findOne(KsAccount, { where: { user_id: userId } })
            if (!ksAccount) {
                const toSave = m.create(KsAccount, {
                    user_id: userId,
                    name: name || '',
                    ksid: ksid || '',
                    has_live: true
                });
                await m.save(KsAccount, toSave);
            } else {
                await m.update(KsAccount, ksAccount.id, { has_live: true, name: body.name, ksid: body.ksid })
            }
            // 查找房间
            const start_open_time = dayjs(openTime).subtract(10, 'second').toDate();
            const end_open_time = dayjs(openTime).add(10, 'second').toDate();
            room = await m.findOne(KsLiveRoom, { where: { user_id: userId, open_time: Between(start_open_time, end_open_time) } });
        }
        // 房间
        const maxCount = redPackets.map(a => a?.count || 0).reduce((a, b) => a > b ? a : b, 0)
        const entity = m.create(KsLiveRoom, {
            id: room?.id,
            link, 
            name,
            stream_id: shareObjectId || '',
            online: online || 0,
            category: category || '',
            open_time: openTime,
            max_count: maxCount || 0,
            rank: rank || '',
            user_id: userId
        });
        const { id: room_id } = await m.save(KsLiveRoom, entity);
        const toSaveRedPackets = redPackets.map(red => {
            return m.create(KsRedPacket, {
                type: red.type || "",
                count: red.count || 0,
                total: red.total || 0,
                open_time: red.open_time || entity.open_time,
                password: red.password || '',
                text: red.text || '',
                room_id: room_id
            })
        });
        // 口令包
        const reds = await m.save(KsRedPacket, toSaveRedPackets)
        /**
         * 存入缓存
         */
        await useRedis(0, async r => {
            await addRoomInfo2({
                ...entity,
                ksid,
                owner,
                uuid: body.uuid,
                reds
            }, r, ['快币', '口令', '穿云箭'])
        });
        await useRedis(7, async r => {
            const core = new Core(r)
            entity.open_time = dayjs(entity.open_time, 'YYYY-MM-DD HH:mm:ss').toDate()
            core.addLiveRoomWithReds(entity, reds)
        });
        return room_id;
    });
    // 加入到redis缓存
    return toSuccess(room_id)
}


/**
 * 抓到红包后 
 * 将红包信息 加入到缓存
 * 红包类型
 * 
 * 红包信息
 * 
 * hset(redpackets, red_id，过期时间)
 * 
 * 红包池：
 * key: 红包类型.owner
 * vlaue: [] sort set
 * zadd(红包类型.owner, { red_id: count })
 * 
 * 红包派发池
 * 
 * 
 * 红包中币池
 * 
 * key: room_id + owner
 * value:  { link, name, user_id, room_id, money_v }
 * expir: open_time
 */